// 小数相加
function litterNumAdd(a1, a2) {
    let len1 = a1.toString().split(".")[1].length;  // 一定要先转换成字符串
    let len2 = a2.toString().split(".")[1].length;
    let length = Math.max(len1, len2);
    let flow = Math.pow(10, length)
    return (a1 * flow + a2 * flow) / flow
}

console.log("小数相加", litterNumAdd(0.1, 0.2))

// 大数相加
function bignumAdd(a1, a2) {
    let len1 = a1.toString().length;
    let len2 = a2.toString().length;
    let length = Math.max(len1, len2)
    let num1 = a1.toString().padStart(length, 0); // padstart 的用法是先
    let num2 = a2.toString().padStart(length, 0);
    let m = 0;
    let j = 0;
    let str = ""
    for (let i = length - 1; i >= 0; i--) {
        let total = parseInt(num1[i]) + parseInt(num2[i]) + j * 1   // 格式转换
        m = total % 10;
        j = Math.floor(total / 10)
        str = m + str
    }
    if (j == 1) {   // 这里是1 最大18 可能存在进1位
        str = "1" + str
    }
    return str
}
console.log("大数相加", bignumAdd(99, 99))

// 大数相乘
function bigNumMul(a1, a2) {
    let len1 = a1.toString().length;
    let len2 = a2.toString().length;    //一定要注意转字符串
    let arr = [];
    for (let i = len1 - 1; i >= 0; i--) {
        for (let j = len2 - 1; j >= 0; j--) {
            let h = i + j;
            let n = i + j + 1;
            let total = a1.toString()[i] * a2.toString()[j] + (arr[n] * 1 || 0);
            arr[h] = Math.floor(total / 10) + (arr[h] || 0)  // 是靠前的位置要加
            arr[n] = total % 10
        }
    }
    console.log(arr)
    return arr.join("").replace(/\^0+/, "") // 正则需要处理正确
}

console.log("大数乘", bigNumMul(89, 87))


// https://segmentfault.com/a/1190000015979292